package com.ciei.dpagm.websocket;

import com.ciei.dpagm.common.service.BaseWebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/webSocket/ConnectWebSocket")
@Component
public class ConnectWebSocketServer extends BaseWebSocketServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConnectWebSocketServer.class);

    /*静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;

    /*concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static CopyOnWriteArraySet<ConnectWebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();


    /**
     * 连接建立成功调用的方法
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;   //加入set中
        webSocketSet.add(this);
        addOnlineCount();  //在线数加1
        LOGGER.info("ConnectWebSocketServer：有新连接加入！当前在线客户端为：" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();
        LOGGER.info("ConnectWebSocketServer：有一连接关闭！当前在线客户端为" + getOnlineCount());
    }

    /**
     *  收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session
     */
    @Override
    @OnMessage
    public void onMessage(String message, Session session) {
        super.onMessage(message, session);
        LOGGER.info("ConnectWebSocketServer：来自客户端的控制命令:" + message);
    }

    public void sendInfo(String message){
        if(webSocketSet != null){
            for (ConnectWebSocketServer item : webSocketSet) {
                item.sendMessage(message);
            }
        }
    }

    /**
     * 获得当前在线人数
     * @return
     */
    public static synchronized int getOnlineCount(){
        return onlineCount;
    }

    /**
     * 在线人数+1
     */
    public static synchronized void addOnlineCount() {
        ConnectWebSocketServer.onlineCount++;
    }

    /**
     * 在线人数-1
     */
    public static synchronized void subOnlineCount() {
        ConnectWebSocketServer.onlineCount--;
    }
}
